<template>
    <div class="sms-container">
        <el-form ref="smsLoginForm" :model="smsFormData" status-icon :rules="smsRules" label-width="120px"
            class="demo-smsFormData">
            <!-- 输入手机号 -->
            <el-form-item label="手机号" prop="phone" class="captcha">
                <el-input v-model="smsFormData.phone" maxlength="11" />
                <span @click="sendSms">{{ desc }}</span>
            </el-form-item>

            <!-- 输入验证码 -->
            <el-form-item label="验证码" prop="code">
                <el-input v-model="smsFormData.code" maxlength="5" type="text" autocomplete="off"
                    @keydown.enter="submitForm(smsLoginForm)" />
            </el-form-item>
            <el-form-item>

                <!-- 切换短信登录 -->
                <el-button type="primary" @click="submitForm(smsLoginForm)">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script setup>
//业务:

//1.修改表单注入的数据以及prop
//2.给smsLogin这个组件添加自己的表单form校验规则
import * as api from "@/api/users"
import { reactive, ref, onUnmounted } from 'vue'
import { ElLoading, ElMessage } from "element-plus"
//引入校验函数
import { smsRules, useSubmitForm } from "../../composition/login/validate"
// 引入路由对象
import { useRouter } from "vue-router"
//引入store
import { useUser } from "@/store/users";

//使用路由对象
let router = useRouter()
// 使用store
let userStore = useUser()
// 表单校验成功会后，回调的方法
let validateSuccess = async () => {
    // console.log('校验成功')
    //发起登入请求的时候就要加载loading加载动画框
    let loadingInstance = ElLoading.service({
        text: '正在登录中...',
        background: 'rgba(0,0,0,.4)'
    })
    //发送短信登入的请求
    try {
        let res = await api.smsLoginApi(smsFormData.code);
        console.log(res);
        //关闭loading加载动画框
        loadingInstance.close()
        // console.log(res)
        //存储token,存到sessionStorage中
        sessionStorage.setItem("cxk", res.data.token);
        //存储用户信息
        userStore.$patch({
            userInfo: res.data.userInfo
        });
        //页面要跳转
        router.push("/")
    } catch (e) {
        console.log(e)
        //登入失败,也要关闭Loading动画
        loadingInstance.close()
    }

    console.log('校验成功');
}
// 表单校验失败之后，回调的方法
let validateFaild = () => {
    console.log('校验失败');
}

//使用submitForm
let submitForm = useSubmitForm(validateSuccess, validateFaild)
const smsLoginForm = ref()
//注入到表单的数据
const smsFormData = reactive({
    phone: "",
    code: ''
})

//短信登入流程

//1.输入手机号,点击发送按钮,获取短信验证码
//短信验证码需要进行倒计时提示
//手机验证码同一个手机,一分钟只能发送一次,一天一个手机号只能发6次
//2.输入短信验证码,进行登入请求
let desc = ref('点击发送短信')
//声明响应式变量,用于展示按钮正在倒计时的文字
//引用定时器,便于组件卸载的时候,清除定时器
let timeDownInterval = null;


//处理用户频繁点击的问题
//1.应用开关的思路
//初始值用户未点击
let isClick = false;

let sendSms = async () => {
    if (!isClick) {
        try {
            //调用接口,获取手机验证码
            let res = await api.getSmsCodeApi(smsFormData.phone);
            // console.log(res);
            ElMessage.success('短信发送成功,请查看手机短信')

            // 提示短信发送成功
            //调用倒计时函数
            timeDownInterval = timeDown(30, desc, '秒后发送', desc.value, () => {
                // console.log('倒计时结束')  
                //把开关重置为关闭状态
                isClick = false
            })


        } catch (e) {
            console.log(e)
            //将按钮的开关重置
            isClick = false
            //  console.log('catch',isClick)
            ElMessage({
                message: e,
                type: 'error',
            })
            return
        }
    }
    //标记isClick已经被点击了
    isClick = true;
    console.log('out', isClick)
}


//短信倒计时的方法
/**
 * @param {Number} timer 倒计时的时间
 * @param {Object} param 需要变更的响应式变量
 * @param {String} msg 倒计时秒数的文字 
 * @param {String} endMsg 倒计时结束之后,回显的文字
 * @param {Function} cb 倒计时结束之后回调的函数
 */

//封装的思路,目的就是为了让使用能够变简单,复杂的逻辑放在函数内部

//字符串.padStart('希望保留几位数','用什么字符去补')

let timeDown = (timer = 5, param, msg, endMsg, cb) => {
    //实现思路,核心就是间隔定时器
    let count = timer;
    //一调用倒计时函数,就要显示倒计时的秒数
    // count是number类型需要转成字符串才能调用padStart方法
    param.value = (count + "").padStart(2, 0) + msg;
    let interval = setInterval(() => {
        count--
        if (count <= 0) {
            //清除定时器
            clearInterval(interval)
            //倒计时结束重新变成初始的点击发送状态
            param.value = endMsg
            //回调传入的函数
            cb && cb()
            return
        }
        param.value = (count + "").padStart(2, 0) + msg
    }, 1000)
    //返回定时器的引用
    return interval
}

//在组件卸载的时候,清除定时器
onUnmounted(() => {
    //卸载定时器
    console.log('组件被卸载了')
    clearInterval(timeDownInterval)
})

</script>




<style scoped lang="scss">
.captcha {
    display: flex;

    :deep(.el-input) {
        width: 152px;
        border-right: none;

        .el-input__wrapper {
            border-radius: 5px 0 0 5px;
            box-shadow: none;
        }
    }

    span {
        height: 42px;
        background-color: #fff;
        display: inline-block;
        border-left: none;
        border-radius: 0 5px 5px 0;
        width: 39%;
        color: #666;
        font-size: 14px;
        font-weight: 900;
        line-height: 42px;
        cursor: pointer;
        text-decoration: underline;
    }
}

.el-form {
    padding-right: 50px;
    margin-left: -20px;
    overflow: hidden;

    :deep(.el-button--primary) {
        height: 40px;
        width: 250px;
        // position: relative;
        // left: 0px;
        background: linear-gradient(90deg, #1596fb, #002dff)
    }
}

:deep(.el-form-item__label) {
    color: #fff;
    line-height: 40px
}

:deep(.el-input__inner) {
    height: 40px;
    width: 100%;
}

:deep(.el-form-item__content) {
    width: 150px;
}
</style>